
import React from 'react'
import { BasePage, UdPage, UdPageHeader, udConfigProvider, http, routeUtils, UdTable} from '@/lib'
import { RouteComponentProps } from 'react-router-dom'
import classNames from 'classnames'
import { Spin, BackTop, Tag, Tabs} from 'antd'
import { getTableColumns, ETabTypes, getTabRequestData } from './common'
import apis from '@/apis/CustomerManage'
const { TabPane } = Tabs


const initTabTypes: any = [
  {
    title: '所属品牌公司',
    key: ETabTypes.BRAND_COMPANY,
  },
  {
    title: '经销产品及区域',
    key: ETabTypes.PRODUCT_AREA,
  },
  {
    title: '扫码主考核客户',
    key: ETabTypes.SCANNING_CODE,
  }
]

export default class Index extends BasePage<ICustomerDetailProps, ICustomerDetailState> {
  protected pageContainer = udConfigProvider.ui.getPageContainer()
  /** 默认查询参数 */
  protected defaultQueryParams: any = {
    page: 1,
    size: 10,
    conditions: {},
    v: 0
  } as any
  public tabTypes: any = [...initTabTypes]
  public agentTypeEnum = {
    0: '经销商',
    1: '分销商',
    null: '终端',
  }
  constructor(props) {
    super(props)
    this.state = {
      title: ' ',
      subTitle: '经销商',
      querying: false,
      showTabKey: '0',
      tabDatas: {},
      tabPageDatas: {},
      tableProps: {
        scroll: { x: true },
        expandedRowRender: this.expandedRowRender,
        onExpand: this.onExpand,
      },
    }
  }
  public componentWillMount() {
    super.componentWillMount()
    this.query()
    const { agentName } = routeUtils.searchStringToObject(this.props.location.search, { agentName: '' })
    const agentType = this.props.match.params.type
    this.formatTabs(agentType)
    this.setState({
      title: agentName,
      subTitle: this.agentTypeEnum[agentType],
    })
  }
  public componentWillReceiveProps(nextProps) {
    if (nextProps.match.params.id !== this.props.match.params.id) {
      const { agentName } = routeUtils.searchStringToObject(nextProps.location.search, { agentName: '' })
      const agentType = nextProps.match.params.type
      this.formatTabs(agentType)
      this.setState({
        title: agentName,
        subTitle: this.agentTypeEnum[agentType],
        showTabKey: '0',
        tabDatas: {}, // 重置tab数据
        tabPageDatas: {}, // 重置tab分页数据
      }, () => this.query())
    }
  }
  render() {
    const { title, subTitle, querying, showTabKey } = this.state
    const subTitleNode = <Tag color="red">{subTitle}</Tag>
    return (
      <UdPage className={classNames('detail-page')}>
        {
          title && <UdPageHeader title={title} subTitle={subTitleNode}
            onBack={this.onBack}
            affixProps={{ target: () => this.pageContainer }} />
        }
        <Spin spinning={querying}>
          <div className="detail-body">
            <Tabs activeKey={showTabKey} onChange={this.switchTabsHandle}>
              {this.tabTypes.map(item => (
                  <TabPane tab={item.title} key={item.key} disabled={item.disabled}>
                  {showTabKey == item.key && this.getShowTab(item.key)}
                </TabPane>
              ))}
            </Tabs>
          </div>
        </Spin>
        {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}

      </UdPage>
    )
  }

  public query = (queryParams?) => {
    const { tabDatas, tabPageDatas, showTabKey } = this.state
    const agentId = this.props.match.params.id
    this.setState({ querying: true })
    const searchString = this.props.location.search
    const { url, params } = getTabRequestData(Number(showTabKey), agentId, searchString, queryParams)
    http.get(url, { params }).then(res => {
      let data
      if (Number(showTabKey) == ETabTypes.BRAND_COMPANY || Number(showTabKey) == ETabTypes.SCANNING_CODE) {
        // 所属品牌公司 || 扫码主考核客户 无分页数据
        data = res.data
      } else {
        data = res.data.content
        const pagination: any = {}
        pagination.current = res.data['number']
        pagination.pageSize = res.data['size']
        pagination.total = res.data['totalElements']
        tabPageDatas[showTabKey] = pagination
      }
      tabDatas[showTabKey] = data
      this.setState({
        tabDatas,
        tabPageDatas,
      })
    }).finally(() => {
      this.setState({ querying: false })
    })
  }

  public onBack = () => {
    this.props.history.goBack()
  }

  public formatTabs = (type) => {
    if (type == 0) {
      // 经销商
      this.tabTypes = [...initTabTypes]
    } else if (type == 1) {
      // 分销商 除下级客户(分销商)所有
      this.tabTypes = initTabTypes.filter(tab => tab.key !== ETabTypes.SPECIAL_DELEAR)
    } else if (type == 'null') {
      // 终端 只显示产品及区域
      this.tabTypes = initTabTypes.filter(tab => tab.key === ETabTypes.PRODUCT_AREA)
    }
  }

  public switchTabsHandle = (key) => {
    this.setState({
      showTabKey: key,
    }, () => {
      // this.pushQueryParams({showTabKey:key},false)
      const { tabDatas } = this.state
      if (!tabDatas[key] || !tabDatas[key].length) {
        this.query()
      }
    })
  }
  // 展开
  private expandedRowRender = (recode) => {
    console.log(recode);
    let columns = [
      // { title: '员工姓名', dataIndex: 'userName', key: 'userName' },
      // { title: '员工手机号', dataIndex: 'phone', key: 'phone' },
      // { title: '客户编码', dataIndex: 'agentCode', key: 'agentCode' },
      // { title: '客户名称', dataIndex: 'agentName', key: 'agentName' },
      // { title: '角色', dataIndex: 'roleName', key: 'roleName' },
      // { title: '状态', dataIndex: 'isValid', key: 'isValid' },
      // { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
      // { title: '创建人', dataIndex: 'createBy', key: 'createBy' },
      // { title: '最近修改人', dataIndex: 'updateBy', key: 'updateBy' },
      { title: '区域编码', dataIndex: 'areaCode', key: 'areaCode' },
      { title: '区域名称', dataIndex: 'areaName', key: 'areaName' },
    ]
    const dataSource = this.state.tabDatas[recode.id] || []
    return (
      <UdTable columns={columns} dataSource={dataSource} pagination={false} rowKey="id" />
    )
  };
  // 展开后调用的方法
  private onExpand = (expanded,record) => {
    if (!expanded) return null
    http.get(apis.areaDetails, { params: { agentId: String(record.id)} }).then(resp => {
      let value = { ...this.state.tabDatas }
      value[record.id] = resp.data
      this.setState({
        tabDatas: value,
      })
    })
  }
  // 获取片区详情
  public getShowTab = (key) => {
    const { querying } = this.state
    const dataSource = this.state.tabDatas[key] || []
    const pagination = this.state.tabPageDatas[key] || false
    const { history } = this.props
    let columns = getTableColumns(key, history)
    return (
      <div>
        <UdTable
          rowKey='id'
          columns={columns}
          dataSource={dataSource}
          loading={querying}
          pagination={pagination}
          onExpand={this.onExpand}
          expandedRowRender={this.expandedRowRender}
          onChange={this.handleTableChange}
        />
      </div>
    )
  }
  /**
   * 列表检索条件发生改变时
   */
  protected handleTableChange = (pagination, filters, sorter, extra) => {
    const { current: page, pageSize: size } = pagination
    const { showTabKey } = this.state
    const params = {
      page,
      size,
      showTabKey,
    }
    this.query(params)
  }

  protected queryParamsChanged = () => {
    console.log('queryParamsChanged', this.queryParams)
    this.query()
  }

}

interface ICustomerDetailProps extends RouteComponentProps<{
  id: string
  type: string
}> {

}

interface ICustomerDetailState {
  title?: string
  subTitle?: string
  querying?: boolean
  showTabKey: string
  tabDatas: any
  tabPageDatas: any,
  tableProps:any
}